import cv2
import numpy as np

# 指纹的方向梯度直方图特征向量
def calculate_dgh(image, cell_size=8, block_size=2, bins=9):
    # 计算图像梯度
    dx = cv2.Sobel(image, cv2.CV_32F, 1, 0)
    dy = cv2.Sobel(image, cv2.CV_32F, 0, 1)

    # 计算梯度幅值和方向
    magnitude = np.sqrt(dx**2 + dy**2)
    angle = np.arctan2(dy, dx) * (180 / np.pi) % 180  # 计算角度并转换为0-180度范围

    # 划分图像为cell
    cell_rows = image.shape[0] // cell_size
    cell_cols = image.shape[1] // cell_size

    dgh_feature = []

    for i in range(cell_rows):
        for j in range(cell_cols):
            cell_magnitude = magnitude[i * cell_size: (i + 1) * cell_size,
                                       j * cell_size: (j + 1) * cell_size]
            cell_angle = angle[i * cell_size: (i + 1) * cell_size,
                               j * cell_size: (j + 1) * cell_size]

            # 统计每个cell的梯度直方图
            hist, _ = np.histogram(cell_angle, bins=bins, range=(0, 180), weights=cell_magnitude)
            dgh_feature.extend(hist)

    return dgh_feature

if __name__=='__main__':
    # 读取指纹图像
    image = cv2.imread('tmp/fingerprint_image.bmp', cv2.IMREAD_GRAYSCALE)

    # 计算方向梯度直方图特征
    dgh_feature = calculate_dgh(image)

    # 打印特征向量长度和示例特征向量
    print("DGH Feature Length:", len(dgh_feature))
    print("Example DGH Feature Vector:", dgh_feature[:10])  # 打印前10个特征值
